import axios from "axios";
import qs from 'qs';
// 创建axios 并设置响应超时
const instance = axios.create({
    timeout:100000
});
// 请求前拦截器
instance.interceptors.request.use(config => {
    if (config.method == 'post' || config.method == 'put') {
        config.data = config.data || {}
        // 区分登录接口，登录接口不需要传token
        if(localStorage.getItem('token')){
            config.data.token = localStorage.getItem('token')
        }
        // post 转换数组 请求接受的是id=1&id=2
        config.data = qs.stringify(config.data,{ arrayFormat:'repeat',allowDots:true})
    }else if(config.method == 'delete' || config.method == 'get'){
        config.params.token = localStorage.getItem('token')
        // get 转换数组
        config.url = config.url + "?" + qs.stringify(config.params,{arrayFormat:'repeat'})
        delete config.params
    }
    return config;
},error=>{
    return Promise.reject(error);
})

// 响应前拦截器
instance.interceptors.response.use(result => {
    return result.data;
}, error => {
    return Promise.reject(error);
});

export default instance